<?php
// +----------------------------------------------------------------------
// | my
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\model;

use think\Model;

class Node extends Model
{

    protected $table = "my_admin_node";
    protected $insert = ['status'=>1,'aid'=>1];  
    protected $autoWriteTimestamp = true;

    /**
     * 获取节点数据
     */
    public function getNodeInfo($id)
    {
        $result = $this->field('id,node_name,typeid')->select();
        $str = "";

        $role = model('User');
        $rule = model('Role')->getRuleById($id);

        if(!empty($rule)){
            $rule = explode(',', $rule);
        }
        foreach($result as $key=>$vo){
            $str .= '{ "id": "' . $vo['id'] . '", "pId":"' . $vo['typeid'] . '", "name":"' . $vo['node_name'].'"';

            if(!empty($rule) && in_array($vo['id'], $rule)){
                $str .= ' ,"checked":1';
            }

            $str .= '},';

        }

        return "[" . substr($str, 0, -1) . "]";
    }

    /**
     * 根据节点数据获取对应的菜单
     * @param $nodeStr
     */
    public function getMenu($nodeStr = '')
    {
        //超级管理员没有节点数组
        $where = empty($nodeStr) ? 'is_menu = 1' : 'is_menu = 1 and id in('.$nodeStr.')';

        $result = db('admin_node')->field('id,node_name,typeid,control_name,action_name,icon,group')
            ->where($where)->order('sort')->select();
        
      
        $menu = prepareMenu($result);
       

        return $menu;
    }

    /**
     * 删除节点
     * @param $id
     */
    public function delNode($id)
    {
        try{

            $this->where('id', $id)->delete();
            return ['code' => 1, 'data' => '', 'msg' => '删除权限结节成功'];

        }catch( PDOException $e){
            return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
    }

    public function editData(){

      $data=input("post.");
      
      if ($data['id']){
         $res = $this->allowField(true)->update($data);
      }else{
         $res = $this->allowField(true)->data($data)->save();
      }
      return $res;
    }

}